﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ProxyHero.Common;
using System.Threading;
using System.IO;
using ProxyHero.Entity;
using ProxyHero.HttpUility;

namespace ProxyHero.TabPages
{
    public partial class frmProxyView : Form
    {
        #region Variable
        ProxyHelper proxyHelper = new ProxyHelper();
        delegate void DelegateVoid();
        Thread threadTest = null;
        string strIP;
        string strPort;
        #endregion

        public frmProxyView()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            this.dgvProxyList.AutoGenerateColumns = false;
        }

        private void tsmiCopy_Click(object sender, EventArgs e)
        {
            try
            {
                string strProxyServer = GetProxyInfo();
                Clipboard.SetText(strProxyServer);
                Config.MainForm.SetStatusText("已成功复制代理:" + strProxyServer);
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }


        /// <summary>
        /// 获取代理信息
        /// </summary>
        /// <returns></returns>
        private string GetProxyInfo()
        {
            int rowIndex = this.dgvProxyList.CurrentRow.Index;
            return this.dgvProxyList.Rows[rowIndex].Cells[0].Value.ToString() + ":" + this.dgvProxyList.Rows[rowIndex].Cells[1].Value.ToString();
        }

        private void tsmiUseIt_Click(object sender, EventArgs e)
        {
            try
            {
                proxyHelper.SetIEProxy(this.GetProxyInfo(), 1);
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiCancelProxy_Click(object sender, EventArgs e)
        {
            try
            {
                proxyHelper.SetIEProxy("", 0);
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void dgvProxyList_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                if (e.RowIndex > -1)
                {
                    strIP = this.dgvProxyList.Rows[e.RowIndex].Cells[0].Value as string;
                    strPort = this.dgvProxyList.Rows[e.RowIndex].Cells[1].Value as string;

                    if (e.Button == MouseButtons.Right)
                    {
                        this.dgvProxyList.CurrentCell = this.dgvProxyList.Rows[e.RowIndex].Cells[e.ColumnIndex];
                        this.contextMenuStrip1.Show(Control.MousePosition);
                    }
                }
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsbSave_Click(object sender, EventArgs e)
        {
            try
            {
                Save();
                Config.MainForm.SetStatusText("保存成功");
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }
        public void Save()
        {
            if (Config.AvailableProxyData.Rows.Count > 0)
            {
                FileInfo fi = new FileInfo(Config.ProxyFilePath);
                if (!fi.Directory.Exists)
                {
                    fi.Directory.Create();
                }

                if (!fi.Exists)
                {
                    fi.Create();
                }
                GC.Collect();

                string[] result = TxtHelper.WriteProxyTxt(Config.AvailableProxyData, fi.FullName, Encoding.UTF8);

                if (result[1] != "") MsgBox.ShowMessage(result[1]);
            }
        }

        private void tsmiTest_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.strIP) ||
                     string.IsNullOrEmpty(this.strPort))
                {
                    Config.MainForm.SetStatusText("请先设置代理服务器，再验证！");
                    return;
                }

                DelegateVoid delegateTest = new DelegateVoid(this.Test);
                threadTest = new Thread(new ThreadStart(delegateTest));
                threadTest.Start();
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        /// <summary>
        /// 验证代理
        /// </summary>
        private void Test()
        {
            DelegateVoid delegateVoid = new DelegateVoid(this.EnableThis);
            this.Invoke(delegateVoid);

            Config.MainForm.SetStatusText("正在验证代理请稍后...");
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            ProxyEntity setting = this.GetProxySetting();
            DataRow[] drs = Config.AvailableProxyData.Select("IP='" + setting.Ip + "' and Port ='" + setting.Port.ToString() + "'");
            Config.MainForm.SetStatusText("正在验证...");

            try
            {
                TestEntity te = new TestEntity();

                #region 读取验证配置
                if (Config._localConfig == null)
                {
                    Config._localConfig = XmlHelper.XmlDeserialize(
                        Config.ConfigPath,
                        typeof(ConfigEntity)) as ConfigEntity;
                }

                if (Config._localConfig.DefaultTestUrl != null)
                {
                    te = Config._localConfig.DefaultTestUrl;
                }
                #endregion

                if ((bool)HttpHelper.TestProxy(setting, te)[0])
                {
                    Config.MainForm.SetStatusText("此代理有效！耗时：" + sw.ElapsedMilliseconds.ToString("F0") + "毫秒。");
                    drs[0]["Speed"] = double.Parse(sw.ElapsedMilliseconds.ToString("F0"));
                }
                else
                {
                    Config.AvailableProxyData.Rows.Remove(drs[0]);
                    Config.MainForm.SetStatusText("此代理无效！");
                }
            }
            catch (Exception ex)
            {
                try
                {
                    Config.AvailableProxyData.Rows.Remove(drs[0]);
                    Config.MainForm.SetStatusText(ex.Message);
                }
                catch (Exception)
                { }
            }
            finally
            {
                if (Config.AvailableProxyData.Rows.Count > 0)
                {
                    BindDataGrid();
                }
            }

            this.Invoke(delegateVoid);
        }

        /// <summary>
        /// 获取代理设置
        /// </summary>
        /// <returns></returns>
        public ProxyEntity GetProxySetting()
        {
            try
            {
                ProxyEntity setting = new ProxyEntity();

                if (string.IsNullOrEmpty(this.strIP))
                {
                    strIP = this.dgvProxyList.Rows[dgvProxyList.CurrentRow.Index].Cells[0].Value as string;
                }

                setting.Ip = this.strIP;

                if (string.IsNullOrEmpty(this.strPort))
                {
                    strPort = this.dgvProxyList.Rows[dgvProxyList.CurrentRow.Index].Cells[1].Value as string;
                }

                setting.Port = int.Parse(this.strPort);

                setting.ProxyType = 2;
                setting.UserName = string.Empty;
                setting.Password = string.Empty;
                return setting;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void EnableThis()
        {
            this.dgvProxyList.Enabled = !this.dgvProxyList.Enabled;
        }

        private void tsmiDelete_Click(object sender, EventArgs e)
        {
            DeleteProxy();
        }

        public void BindDataGrid()
        {
            this.dgvProxyList.DataSource = Config.AvailableProxyData;
            this.dgvProxyList.Refresh();
            Statistics();
            DelegateVoid dv = new DelegateVoid(this.Save);
            this.Invoke(dv);
        }

        private void tsbDelete_Click(object sender, EventArgs e)
        {
            DeleteProxy();
        }
        /// <summary>
        /// 删除代理
        /// </summary>
        public void DeleteProxy()
        {
            ProxyEntity setting = this.GetProxySetting();
            DataRow[] drs = Config.AvailableProxyData.Select("IP='" + setting.Ip + "' and Port ='" + setting.Port.ToString() + "'");
            if (drs.Length > 0)
            {
                Config.AvailableProxyData.Rows.Remove(drs[0]);
                BindDataGrid();
                this.strIP = "";
                this.strPort = "";
            }
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes == MsgBox.ShowQuestionMessage("确定要清空列表中数据吗？"))
            {
                FileInfo fi = new FileInfo(Config.ProxyFilePath);
                if (fi.Exists)
                {
                    fi.Delete();
                    GC.Collect();
                }

                Config.AvailableProxyData.Rows.Clear();
                BindDataGrid();
            }
        }

        private void tsbAutoChangeProxy_Click(object sender, EventArgs e)
        {
            SetAutoChange();
        }

        public void SetAutoChange()
        {
            if (!(Config.LocalConfig.IsCooperation && ProxyHelper.GetStartPage(Config.IEStartPage)))
            {
                MsgBox.ShowMessage("请在选项中设置成合作版才能使用此功能！");
                return;
            }

            if (Config.AvailableProxyData.Rows.Count > 0)
            {
                if (this.tsbAutoChangeProxy.Text == "开启自动切换代理")
                {
                    if (DialogResult.Yes == MsgBox.ShowQuestionMessage("请确认代理应用于IE还是内置浏览器？\n点击“是”应用于Internet Explorer。\n点击“否”应用于内置浏览器。"))
                    {
                        Config.ProxyApplicatioin = "IE";
                    }
                    else
                    {
                        Config.ProxyApplicatioin = "LB";
                    }
                    StartAutoChange();
                }
                else
                {
                    StopAutoChange();
                }
            }
            else
            {
                MsgBox.ShowMessage("可用代理列表为空，不能自动切换代理！");
            }
        }

        /// <summary>
        /// 启动自动代理
        /// </summary>
        public void StartAutoChange()
        {
            this.tsbAutoChangeProxy.Image = ProxyHero.Properties.Resources.timer1;
            this.tsbAutoChangeProxy.Text = "关闭自动切换代理";
            Config.TsCountDown = new TimeSpan(0, Config.LocalConfig.AutoChangeProxyInterval, 0);
            Config.MainForm.timerAutoChangeProxy.Start();
            Config.MainForm.SetAutoChangeLable(Config.MainForm.timerAutoChangeProxy.Enabled);
        }
        /// <summary>
        /// 关闭自动代理
        /// </summary>
        public void StopAutoChange()
        {
            this.tsbAutoChangeProxy.Image = ProxyHero.Properties.Resources.timer2;
            this.tsbAutoChangeProxy.Text = "开启自动切换代理";
            Config.MainForm.timerAutoChangeProxy.Stop();
            Config.MainForm.SetAutoChangeLable(Config.MainForm.timerAutoChangeProxy.Enabled);
        }

        private void tsbImport_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.OpenFileDialog objOpen = new System.Windows.Forms.OpenFileDialog();
            objOpen.Filter = "(*.txt)|*.txt|" + "(*.*)|*.*";

            if (objOpen.ShowDialog() == DialogResult.OK)
            {
                string[] result = TxtHelper.ReadAvaliableProxyTxt(objOpen.FileName, Encoding.UTF8);

                if (result[1] != "")
                {
                    MsgBox.ShowErrorMessage(result[1]);
                }
                else
                {
                    BindDataGrid();
                }
            }
        }

        private void tsbExport_Click(object sender, EventArgs e)
        {

            if (Config.AvailableProxyData.Rows.Count > 0)
            {
                System.Windows.Forms.SaveFileDialog objSave = new System.Windows.Forms.SaveFileDialog();
                objSave.Filter = "(*.txt)|*.txt|" + "(*.*)|*.*";

                objSave.FileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".txt";
                if (objSave.ShowDialog() == DialogResult.OK)
                {
                    string[] result = TxtHelper.WriteProxyTxt(Config.AvailableProxyData, objSave.FileName, Encoding.UTF8);
                    if (result[1] != "")
                    {
                        MsgBox.ShowErrorMessage(result[1]);
                    }
                }
            }
            else
            {
                MsgBox.ShowMessage("没有数据，无法导出！");
            }
        }

        private void tsbTj_Click(object sender, EventArgs e)
        {
            Statistics();
        }

        private void Statistics()
        {
            this.tsslAvaliableProxyStatus.Text = "共" + this.dgvProxyList.Rows.Count + "条";
        }
    }
}
